/**
 * 时间格式化
 * @param {*} times 时间戳或日期
 * @param {*} isShowTime 是否显示时分秒,默认不显示
 */
const timesToTime = (times, isShowTime = false) => {
    if (times) {
      if (String(times).indexOf("T") > -1 && String(times).indexOf("08:00") < 0) {
        times = times + "+08:00"
      }
      let date = new Date(times);
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
      return !isShowTime ? Y + M + D : Y + M + D + h + m + s;
    } else {
      return ''
    }
  }
  
  /**
   * 列表转树形结构
   * @param {*} oldArr 需转换的数组
   * @param {*} filterFn 过滤数组条件
   */
  const listToTree = (oldArr, filterFn) => {
    const defaultFilterFn = (ele) => ele.ParentID === null
    oldArr.forEach(element => {
      let parentId = element.ParentID;
      if (parentId !== null) {
        oldArr.forEach(ele => {
          if (ele.ID === parentId) { //当内层循环的ID == 外层循环的ParentID时，需要往该内层id里建个children并push对应的数组；
            if (!ele.children) {
              ele.children = [];
            }
            ele.children.push(element);
          }
        });
      }
    });
    oldArr = oldArr.filter(filterFn || defaultFilterFn); //这一步是过滤，按树展开，将多余的数组剔除；
    return oldArr;
  };
  
  const listToStr = (list, value, field = 'Name', bank = 'Title') => {
    list = list.filter(ele => ele[field] === value);
    return list.length ? String(list[0][bank]) : ''
  };
  
  
  
  // 根据返回的ids显示文字
  const filtersFn = (oldArr, ids, field = 'Name', bank = 'Title') => {
    if (oldArr && ids !== '') {
      const filterArr = oldArr.filter(item => ids.includes(item[field]));
      const tempArr = [];
      filterArr.forEach(item => {
        tempArr.push(item[bank])
      });
      return tempArr.join(';')
    }
  }
  
  // 金额格式化
  const moneyFormat = (num, suffix = '00') => {
    num = String(num);
    if (num && num !== 'null') {
      let reg = /(?=(\B)(\d{3})+$)/g;
      let result;
      if (suffix) {
        result = String(num.split('.')[0]).replace(reg, ',') + '.' + Number(num).toFixed(suffix.length).split('.')[1]
      } else {
        result = String(num.split('.')[0]).replace(reg, ',')
      }
      return result
    } else {
      return '';
    }
  };
  
  // 秒转小时
  const secondToHours = (seconds) => {
    if (seconds) {
      let h = Math.floor(seconds / 3600)
      let m = Math.floor((seconds % 3600) / 60)
      let s = Math.floor((seconds % 3600) % 60)
      h = h > 0 ? h + '时' : ''
      m = m > 0 ? m + '分' : ''
      s = s > 0 ? s + '秒' : ''
      return h + m + s;
    }
    return ""
  }
  
  /**
   * 获取唯一标识
   * @param {Number} radix    生成uuid的进制
   * @param {Number} len     生成uuid的长度
   * @returns 
   */
  const uuid = (radix, len) => {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  };
  
  /**
   * menu转树形结构
   * @param {*} arr 需转换的menu数组
   * @param {*} pId 父ID，可以不传
   */
  const menuToTree = (arr, pId) => {
    return arr.filter((item) =>
      pId === undefined ? !item.ParentID : item.ParentID === pId
    ).map((item) => {
      item.children = menuToTree(arr, item.ID);
      return item;
    });
  };
  
  /**
   * 获取文件类型图片
   */
  const getFileTypeImg = (fileName) => {
    const imgType = {
      pciture: /\.(?:jpg|jpeg|png)+(:\d*)*$/i,
      word: /\.(?:doc|docx)+(:\d*)*$/i,
      pdf: /\.(?:pdf)+(:\d*)*$/i,
      excel: /\.(?:xlsx|xls)+(:\d*)*$/i,
      ppt: /\.(?:ppt|pps|pptx)+(:\d*)*$/i,
      zip: /\.(?:zip|rar)+(:\d*)*$/i,
    }
    const keys = Object.keys(imgType)
    let imgSrc = '/static/picture/unknown-file-icon.png'
    for (let i = 0; i < keys.length; i++) {
      let key = keys[i]
      if (imgType[key].test(fileName)) {
        imgSrc = `/static/picture/${key}-file-icon.png`
        break
      }
    }
    return imgSrc
  }
  
  //计算文件大小
  const computedFileSize = (val = 0) => {
    let size = '0B'
    val = Number(val)
    if (val < 0.1 * 1024) {
      // 小于0.1KB
      size = val.toFixed(2) + 'B'
    } else if (val < 0.1 * 1024 * 1024) {
      // 小于0.1MB
      size = (val / 1024).toFixed(2) + 'KB'
    } else if (val < 0.1 * 1024 * 1024 * 1024) {
      // 小于0.1GB
      size = (val / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
      size = ''
    }
    return size
  }
  
  // 验证信息
  
  /**
   * 机算两个日期之间的天数
   * @param {*} times 日期1
   * @param {*} times2 日期2
   */
  const calculationTime = (times, times2) => {
    if (times && times2) {
      const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
      return dayDif(new Date(times), new Date(times2))
    } else {
      return '/'
    }
  }
  
  export default { listToTree, timesToTime, listToStr, filtersFn, moneyFormat, secondToHours, uuid, menuToTree, getFileTypeImg, computedFileSize, calculationTime }
  